import Taro, { switchTab, setNavigationBarTitle, setNavigationBarColor, useDidShow } from '@tarojs/taro'
import { View, Image, Button, Navigator, Form, Input } from '@tarojs/components'
import { AtIcon, AtButton, AtForm, AtInput, AtCountdown } from 'taro-ui'
import React, { useState, useEffect } from 'react'

import api, { getCaptcha, doLogin } from '../../utils/api'
import request from '../../utils/request'
import { useAsyncEffect } from '../../utils/index'

import IconUser from '../../images/icon-user.png'
import IconPassword from '../../images/icon-password.png'
import IconCaptcha from '../../images/icon-captcha.png'

import './forget.less'

let timer = null
function Login() {
  useDidShow(() => {
    setNavigationBarTitle({
      title: '初始化密码'
    })
    setNavigationBarColor({
      backgroundColor: '#f8f8f8',
      frontColor: '#000000'
    })
  })
  useEffect(() => {
    getCaptchaPic()
  }, [])

  const [captchaKey, setCapToken] = useState('')
  const [codeurl, setCodeUrl] = useState('')
  const [username, setPhone] = useState('')
  const [sms_code, setCode] = useState('')
  const [captcha, setCaptcha] = useState('')
  const [countdown, setCountdown] = useState(0)

  const handleCodeChange = (e) => {
    setCode(e.detail.value)
  }
  const handlePhoneChange = (e) => {
    setPhone(e.detail.value)
  }
  const handleCaptcha = (e) => {
    setCaptcha(e.detail.value)
  }

  const getCaptchaPic = async () => {
    try {
      const data = await request(getCaptcha)
      setCapToken(data.verifykey)
      setCodeUrl(data.img)
      setCaptcha('')
    } catch (error) {
      console.log(error)
      Taro.showToast({
        title: '载入远程数据错误',
        icon: 'none'
      })
    }
  }
  const countdownEnd = () => {
    setCountdown(0)
  }
  const onSubmitCode = (e) => {
    if(e.detail.value.username == '') {
      Taro.showToast({
        title: '请输入手机号',
        icon: 'none'
      })
      return;
    }
    if(e.detail.value.captcha == '') {
      Taro.showToast({
        title: '请输入图片验证码',
        icon: 'none'
      })
      return;
    }
    let data = {
      ...e.detail.value,
      captchaKey,
      send_type: 1
    }
    request(api.getCode, 'POST', data).then((data) => {
      console.log(data)
      Taro.showToast({
        title: '发送成功',
        icon: 'none'
      })
      setCountdown(data.expired)
    }).catch(_ => {
      getCaptchaPic()
    })
  }
  const onSubmitData = (e) => {
    console.log(e)
    Taro.login().then(res => {
      if (res.code) {
        if(username == '') {
          Taro.showToast({
            title: '请输入手机号',
            icon: 'none'
          })
          return;
        }
        if(sms_code == '') {
          Taro.showToast({
            title: '请输入短信验证码',
            icon: 'none'
          })
          return;
        }
        if(e.detail.value.password == '') {
          Taro.showToast({
            title: '请输入密码',
            icon: 'none'
          })
          return;
        }
        if(e.detail.value.password !== e.detail.value.confirm_password) {
          Taro.showToast({
            title: '两次密码不一致',
            icon: 'none'
          })
          return;
        }
        let data = {
          ...e.detail.value,
          username,
          sms_code,
          captcha,
          js_code: res.code
        }
        request(api.resetPwd, 'POST', data).then((data) => {
          Taro.showTabBar({
            title: '修改成功',
            icon: 'none'
          })
          Taro.setStorage({
            key: 'loginInfo',
            data: data.info
          })
          Taro.setStorage({
            key: 'token',
            data: data.token
          })
          switchTab({
            url: '/pages/mine/mine'
          })
        }).catch(err => {
          Taro.showToast({
            title: err.msg,
            icon: 'none'
          })
          getCaptchaPic()
        })
      } else {
        getCaptchaPic()
        Taro.showToast({
          title: '登录失败！',
          icon: 'none'
        })
      }
    })

  }
  return (
    <View className='login'>
      <View className='group'>
        <Form className="form" onSubmit={onSubmitCode}>
          <View className="form-item">
            <Image mode='aspectFill' className='icon' src={IconUser} />
            <View className="input">
              <Input onInput={handlePhoneChange} name='username' type='text' placeholder='请输入登录账号'></Input>
            </View>
          </View>
          <View className="form-item">
            <Image mode='aspectFit' className='icon' src={IconCaptcha} />
            <View className="input">
              <Input name='captcha' onInput={handleCaptcha} value={captcha} type='text' className="input" placeholder='验证码'></Input>
              <View className="right">
                <Image className="right-val" onClick={getCaptchaPic} src={codeurl} />
              </View>
            </View>
          </View>
          <View className="form-item border">
            <Image mode='aspectFit' className='icon' src={IconCaptcha} />
            <View className="input">
              <Input name='code' onInput={handleCodeChange} type='text' className="input" placeholder='短信验证码'></Input>
              <View className="right">
                {countdown ?
                  <AtCountdown
                    className="countdown"
                    isShowHour={false}
                    format={{ minutes: ':', seconds: '' }}
                    seconds={countdown}
                    onTimeUp={countdownEnd}
                  /> :
                  <Button formType="submit" className="sms-btn" type="primary">获取验证码</Button>
                }
              </View>
            </View>
          </View>
        </Form>
        <Form className="form" onSubmit={onSubmitData}>
          <View className="form-item">
            <Image mode='aspectFill' className='icon' src={IconPassword} />
            <View className="input">
              <Input name='password' type='password' placeholder='请输入新密码'></Input>
            </View>
          </View>
          <View className="form-item">
            <Image mode='aspectFill' className='icon' src={IconPassword} />
            <View className="input">
              <Input name='confirm_password' type='password' placeholder='请确认新密码'></Input>
            </View>
          </View>
          <Button className="form-button" formType="submit">提 交</Button>
        </Form>
      </View>
    </View>
  )
}

export default Login
